#include "webviewutils.h"

#include <QTcpSocket>
#include <QFile>

#include <unistd.h>

WebviewUtils::WebviewUtils(QObject *parent)
    : QObject(parent) {
    server.listen(QHostAddress::Any,8081);
    QObject::connect(&server,SIGNAL(newConnection()),this,SLOT(newConnection()));
}

QString WebviewUtils::readTextFile(QString path) {
    QString content;

    QFile f(path);

    if(f.open(QFile::ReadOnly)) {
        content = f.readAll();
        f.close();
    }

    return content;
}


bool WebviewUtils::readSocketLine(QTcpSocket *socket, char *buf, int buffSz, int timeoutInMillis) {
    int len = strlen(buf);

    while(1) {
        while(1) {
            if(len>=buffSz) return false;
            if(socket->read(&buf[len],1)==1) {
                if(buf[len]=='\n') {
                    buf[len] = 0;
                    return true;
                } else {
                    ++len;
                }
            } else {
                break;
            }
        }

        if(timeoutInMillis<=0) {
            buf[len] = 0;
            return false;
        }

        if(timeoutInMillis>10) {
            usleep(10 * 1000);
            timeoutInMillis -= 10;
        } else {
            usleep(timeoutInMillis * 1000);
            timeoutInMillis = 0;
        }
    }
    return false;
}

QString WebviewUtils::base64_decode(char *string){
    QByteArray ba;

    ba.append(string);
    return QByteArray::fromBase64(ba);
}

void WebviewUtils::newConnection() {
    char buffer[8*1024];

    qDebug("NEW CONNECTION!");
    QTcpSocket *socket = server.nextPendingConnection();
    socket->waitForReadyRead();

    buffer[0] = 0;
    while(readSocketLine(socket,buffer,8*1024,1000)) {
        char *endPtr;
        if( (strstr(buffer,"GET /")==buffer) && (endPtr=strstr(buffer," HTTP/")) ) {
            if(strstr(buffer,"GET /MAPA")==buffer) {
                qDebug("REQUISICAO MAPA");
                QString header("HTTP/1.0 302 Found\nContent-Type: text/html; charset=UTF-8\nContent-Length: ");
                QString content = readTextFile(":///html/map.html");

                qDebug("ENVIANDO: ");
//                qDebug(header.append( QString::number(content.length())).append("\n\n").toUtf8());
//                qDebug(content.toUtf8());
                socket->write(header.append( QString::number(content.length())).append("\n\n").toUtf8());
                socket->waitForBytesWritten();
                socket->write(content.toUtf8());
                socket->waitForBytesWritten();
            } else {
                QString header("HTTP/1.0 302 Found\nContent-Type: text/html; charset=UTF-8\nContent-Length: ");
                QString content = "<html><html>";
                socket->write(header.append( QString::number(content.length())).append("\n\n").toUtf8());
                socket->waitForBytesWritten();
                socket->write(content.toUtf8());
                socket->waitForBytesWritten();
                qDebug("REQ MESSAGE");
                *endPtr = 0;
                QString r = base64_decode(buffer+5);
                emit requestReceived(r);
            }
        }
        buffer[0] = 0;
    }

    qDebug("CLOSE SOCKET");
    socket->close();

    qDebug("DELETE SOCKET");
    delete socket;

    qDebug("DONE");
}
